package com.share.schedule.simple.schedule;

import com.share.common.utils.IpUtil;
import com.share.schedule.simple.model.db.ScheduleLog;
import com.share.schedule.simple.service.ScheduleJobService;
import com.share.schedule.simple.service.ScheduleLogService;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * @author 01401061 - 孙艳强
 * @date 2020/10/28 14:20
 */
@Data
@Slf4j
public abstract class BaseJob {
    @Autowired
    private ScheduleJobService scheduleJobSvice;
    @Autowired
    private ScheduleLogService scheduleLogService;

    private String getJobCode;

    @ApiOperation("jobCode默认使用实现类的列名,子类重写这个方法即可")
    public String getJobCode() {
        return this.getClass().getSimpleName();
    }

    public void execute() {
        // 开始任务 标准化改造 集群形式
        ScheduleLog scheduleLog = insertLog();

        //业务
        String status = null;
        String expMsg = null;
        String remark = null;
        try {
            remark = doJob();
            status = "1";
        } catch (Exception e) {
            log.error("定时任务执行异常", e);
            status = "2";
            expMsg = e.getMessage();
        }

        // 结束任务 更新结束时间
        updateLog(scheduleLog.getId(), status, remark, expMsg);
    }

    private ScheduleLog insertLog() {
        ScheduleLog taskLog = new ScheduleLog();
        taskLog.setJobCode(getJobCode());
        taskLog.setExeIp(IpUtil.getIp());
        taskLog.setStatus("0");
        taskLog.setBeginTime(new Date());
        taskLog.setCreateTime(new Date());
        int insert = scheduleLogService.insert(taskLog);
        if (insert > 0) {
            return taskLog;
        } else {
            return null;
        }
    }

    private int updateLog(Long id, String status, String remark, String errorMsg) {
        ScheduleLog taskLog = new ScheduleLog();
        taskLog.setId(id);
        taskLog.setStatus(status);
        taskLog.setExpMsg(errorMsg);
        taskLog.setRemark(remark);
        taskLog.setEndTime(new Date());
        return scheduleLogService.updateByPrimaryKeySelective(taskLog);
    }

    @ApiOperation("具体的任务,返回异常信息")
    public abstract String doJob() throws Exception;
}
